/*
*  Copyright (C) 2009  Peter Kist & Jan Ripke
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation, either version 3 of the License, or
*  (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "GfxManagerThread.h"
#include "Manager.h"
#include "Consumer.h"

#include <OgreRoot.h>
#include <OgreWindowEventUtilities.h>

#include <core/Timer.h>
#include <gfx/ogre/gui/MenuManager.h>
#include <gfx/ogre/engine/galaxy/GalaxyConsumer.h>

namespace galaxy {
    namespace gfx {
        namespace ogre3d {

            void GfxManagerThread::operator()() {

                core::Timer      timer;
                Ogre::Root     * root = m_Manager->getRoot ();

                MenuManagerPtr                     menuManager = m_Manager->getMenuManager ();
                Consumer                         * consumer = m_Manager->m_Consumer.get ();
                engine::galactic::GalaxyConsumer * galaxyConsumer = m_Manager->m_GalaxyConsumer;

                m_Manager->m_GfxManagerThread->m_State = core::Thread::THREAD_STATE_RUNNING;
                while (m_Manager->m_GfxManagerThread->m_State == core::Thread::THREAD_STATE_RUNNING) {

                    // house keeping
                    timer.updateTimer ();
                    Ogre::WindowEventUtilities::messagePump();

                    // process the first few incoming events (5 max at the time)
                    consumer->handleDelayedEvents (5);
                    galaxyConsumer->handleDelayedEvents (1);

                    // display current state of ogre on screen
                    root->renderOneFrame();

                    // limit framerate to 40 frames per second.
                    time_duration elapsed = timer.getElapsedDuration ();
                    if (elapsed < milliseconds(25)) {
                        boost::this_thread::sleep(milliseconds(25) - elapsed);
                    }
                }
            }

        } // namespace ogre3d
    } // namespace gfx
} // namespace galaxy